import {jwtVerify} from 'jose';
import {Context, Next} from 'koa';
import {JWT_SIGN} from '@/config';
import {WrapperResponse} from '@/utils/wrapperResponse';

const tokenMiddleware = (whiteList: RegExp[]) => async (ctx: Context, next: Next) => {
    if (whiteList.find(item => item.test(ctx.url))) {
        return next();
    }

    const token = ctx.get('Authorization');
    const {payload} = await jwtVerify(
        token,
        new TextEncoder().encode(JWT_SIGN),
        {algorithms: ['HS256'], typ: 'JWT'}
    );
    if (payload.username === 'xxx') {
        return next();
    }

    ctx.body = WrapperResponse.noAuth('Protected resource, use Authorization header to get access');
    return;
};

export default tokenMiddleware;
